
import { Button, ButtonProps } from "antd";
import React from "react";
import ICapabilityProps from "../interfaces/ICapabilityProps";

/** 功能按钮 */
export default function CapabilityButton<T = any>(props: ICapabilityProps<T> & ButtonProps) {

    const { index = 0 } = props;

    const capability = React.useMemo(() => {
        if (props.capability instanceof Array) {
            return props.capability[0];
        } else {
            return props.capability
        }
    }, [props.capability])

    const expand = capability.useExpand(props.record, index);

    const onClick = React.useCallback(async () => {
        try {
            expand.onClick && await expand.onClick();
        } catch (error) {
            error && console.error(error);
        }
        props.onEnd && await props.onEnd(expand);
    }, [expand, props])

    if (capability.isEnable ? capability.isEnable(props.record, index) : true) {
        return (
            <>
                <Button
                    {...props}
                    key={`${capability.id}${index}`}
                    onClick={onClick}
                    loading={!!expand.loading}
                    disabled={capability.isDisabled ? capability.isDisabled(props.record, index) : false}
                >
                    {capability.title}
                </Button>
                {expand.element}
            </>
        )
    } else {
        return <></>
    }
}  